<?php
/**
 *
 * 转换；帖子内容数据
 *
 * convertTopicContent.php
 * Created by IntelliJ IDEA.
 *
 * @author: hjh <hjh@jf.com>
 *
 * Date: 2017/11/2
 * Time: 10:57
 */

use Circle\TopicContent;
use Common\Bridge;

require dirname(__DIR__) . '/cronBase.php';

class convertTopicContent extends cronBase
{
    const PAGE_SIZE = 200;
    const TABLE_NAME = 'TopicContent';

    public function doDefault()
    {
        $primaryKey = 'TopicId';

        $pdo = Bridge::pdo(Bridge::DB_CIRCLE_W);
        $count = $pdo->select("max(`${primaryKey}`)")
            ->from(self::TABLE_NAME)
            ->getValue();

        echo "DataCount: {$count}\n";

        if ($count > 0) {
            $page = ceil($count / self::PAGE_SIZE);
            echo "buildCircleSearch Start!\n";
            for ($i = 1; $i <= $page; $i++) {

                $start = ($i - 1) * self::PAGE_SIZE;
                $end = $start + self::PAGE_SIZE;

                $pdo = Bridge::pdo(Bridge::DB_CIRCLE_W);
                $data = $pdo->select("*")
                    ->from(self::TABLE_NAME)
                    ->where(["{$primaryKey} >" => $start, "{$primaryKey} <=" => $end])
                    ->getAll();

                $pdo->close();
                Bridge::pdo(Bridge::DB_CIRCLE_W, 'force_close');
                $pdo = null;

                foreach ($data as $item) {
                    $content = json_decode($item[TopicContent::FIELD_CONTENT], true);

                    if (isset($content[TopicContent::FIELD_CONTENT_HTML_CONTENT])) {
                        continue;
                    }
                    $content = json_encode(TopicContent::parseContentFromApi($content), JSON_UNESCAPED_UNICODE);
                    //var_dump($content);
                    \Circle\TopicContent::update($item['TopicId'], ['Content' => $content]);
                }

                sleep(1);
                echo "Process: {$i}/{$page}\r";
            }

            echo "\nDone!\n";
        }
    }
}

$app->run();
